#! /usr/bin/env python
# -*- coding: utf8 -*-

import pygtk
pygtk.require('2.0')

import gtk
import sys

if sys.version_info[:2] == (2, 5):
    from xml.etree import ElementTree as et
else:
    from elementtree import ElementTree as et

class transformation(object):
    def __init__(self):
        self.__widgets = []
        self._mxml = []

        b1 = gtk.ScrolledWindow()
        self.__algo_view  = gtk.TreeView()
        self.__algo_store = gtk.TreeStore(str)
        self.__algo_view.set_model(self.__algo_store)
        self.__algo_view.connect("button-press-event", self.algo_view_press)
        self.__algo_view.append_column(gtk.TreeViewColumn("Algorithms", gtk.CellRendererText(), text = 0))
        b1.add(self.__algo_view)
        b1.set_size_request(-1, 200)
        b1.set_sensitive(True)

        b2 = gtk.HBox()
        self.__probability = gtk.Entry()
        self.__ok_btn = gtk.Button("Save")
        self.__ok_btn.connect("clicked", self.probability_save)
        self.__ok_btn.connect("activate", self.probability_save)
        self.__probability.connect("activate", self.probability_save)

        self.__ok_btn.set_sensitive(False)
        self.__probability.set_sensitive(False)

        b2.pack_start(self.__probability, True, True, 5)
        b2.pack_start(self.__ok_btn, False, False, 5)      

        self.__widgets.append(gtk.Label("Algorithms configuration:"))
        self.__widgets.append(b1)
        self.__widgets.append(gtk.Label("Use probability:"))
        self.__widgets.append(b2)


        map(lambda x:x.show_all(), self.__widgets)
        map(lambda x:x.show_all(), self._mxml)
        self.__algorithms = []
        self.__probabilities = {}

    def probability_save(self, widget):
        try:
            valor = int(self.__probability.get_text().strip())
        except ValueError:
            return

        self.__probabilities[self.__current_algo] = valor

    def add_algorithm(self, name):
        self.__algo_store.append(None, name)
        self.__algorithms.append(name)

    def append_elements(self, parent, isXXML=True):
        toAdd = self.__widgets[::]
        if isXXML:
            toAdd += self._mxml

        for i in toAdd:
            parent.pack_start(i)
            parent.reorder_child(i, len(parent) - 2)

    def remove_elements(self):
        [x.parent.remove(x) for x in self.__widgets + self._mxml if x.parent != None]

    def clean_up(self):
        self.__probability.set_text("")
        self.__algo_store.clear()
        [self.__algo_store.append(None, x) for x in self.__algorithms]
        self.__current_algo = []
        self.__probabilities.clear()

    def algo_view_press(self, widget, event):
        if event.type == gtk.gdk._2BUTTON_PRESS and event.button == 1:
            name = self.__algo_store.get_value(self.__algo_view.get_selection().get_selected()[1], 0)

            if name == "":
                return

            self.__current_algo = name

            if name in self.__probabilities:
                self.__probability.set_text("%d" % (self.__probabilities[name], ))
            else:
                self.__probability.set_text("")

            self.__ok_btn.set_sensitive(True)
            self.__probability.set_sensitive(True)

    def xml(self, name, transform_type):
        node = et.Element("transformation")

        if transform_type == "mxml":
            nname = et.Element("name")
            nname.text = name

            chars = et.Element("chars")

            map(node.append, [nname, chars])
            for i in self.__probabilities:
                nn = et.Element("useAlgo")
                name = et.Element("name")
                name.text = i

                prob = et.Element("useProb")
                prob.text = "%d" % self.__probabilities[i]

                map(nn.append, [name, prob])
                chars.append(nn)

        else:
            nname      = et.Element("name")
            nname.text = name

            algos = et.Element("useAlgorithms")

            map(node.append, [nname, algos])

            for i in self.__probabilities:
                nn = et.Element("useAlgorithm")
                name = et.Element("name")
                name.text = i

                prob = et.Element("probability")
                prob.text = "%d" % self.__probabilities[i]

                map(nn.append, [name, prob])
                algos.append(nn)

        return node

class root(object):
    def __init__(self):
        self.__widgets = []

        # self.__widgets.append(gtk.Label("Probability distribution:"))
        # self.__distro_combo = gtk.combo_box_new_text()
        # self.__widgets.append(self.__distro_combo)
        # self.__distro_combo.set_sensitive(True)

        self.__widgets.append(gtk.Label("Selection probability distribution:"))
        self.__selection_combo = gtk.combo_box_new_text()
        self.__widgets.append(self.__selection_combo)
        self.__selection_combo.set_sensitive(True)

        b1 = gtk.HBox()
        b1.pack_start(gtk.Label("Copy rate (%):"), False, False, 5)
        self.__copy_rate = gtk.Entry()
        b1.pack_start(self.__copy_rate, True, True, 5)

        b2 = gtk.HBox()
        b2.pack_start(gtk.Label('"Untouched" rate (%):'), False, False, 5)
        self.__untouched_rate = gtk.Entry()
        b2.pack_start(self.__untouched_rate, True, True, 5)

        self.__widgets.append(b1)
        self.__widgets.append(b2)

    def append_elements(self, parent):
        for i in self.__widgets:
            parent.pack_start(i, False, False, 5)
            parent.reorder_child(i, len(parent) - 2)
            i.set_sensitive(True)
            i.show_all()

    def remove_elements(self):
        [x.parent.remove(x) for x in self.__widgets if x.parent != None]

    def add_distribution(self, name):
        # self.__distro_combo.append_text(name)
        self.__selection_combo.append_text(name)

    def xml(self, name):
        node = et.Element("transformation")

        isRoot = et.Element("isRoot")
        isRoot.text = "True"

        copyRate = et.Element("copyRate")
        copyRate.text = self.__copy_rate.get_text()

        untouched = et.Element("untouched")
        untouched.text = self.__untouched_rate.get_text()

        select_prob = et.Element("selectProbDistr")
        select_prob.text = self.__selection_combo.get_model()[self.__selection_combo.get_active()][0]

        # prob = et.Element("useProbDistr")
        # prob.text = self.__distro_combo.get_model()[self.__distro_combo.get_active()][0]

        nname = et.Element("name")
        nname.text = name

        map(node.append, [nname, select_prob, untouched, copyRate, isRoot])

        return node
